import { getShopIdData, getShopInfo } from '../api/webPageAip/product'
import jwt from 'jsonwebtoken'
import { jwtConfig } from '../config/index'
import ApiError from '../error/ApiError'
import ApiErrorNames from '../error/ApiErrorNames'

export const getshopid = async (ctx) => {
	if (!ctx.header.t) {
		return {
			code: 0,
			data: {
				shop_id: ctx.query.shop_id
			}
		}
	}
	// const web_id =
	// 	ctx.header.t &&
	// 	ctx.header.t
	// 		.split(';')
	// 		.map((item) => {
	// 			const itemkey = item.split('=')
	// 			// console.log('itemkey', itemkey)
	// 			return {
	// 				key:itemkey[0] && itemkey[0].trim(),
	// 				value: itemkey[1] &&  itemkey[1].trim(),
	// 			}
	// 		})
	// 		.find((item) => item.key === 's_v_web_id')['value']
	// ctx.query.fp = web_id
	// ctx.query.verifyFp = web_id
	const shopId = await getShopIdData(ctx)
	if (!shopId.code) {
		shopId.data.shop_id = shopId.data.id
	}
	return shopId
}

export const getshopinfo = async (ctx) => {
	ctx.query.version = '0'
	const shopInfo = await getShopInfo(ctx)
	return shopInfo
}

export const getjwtdata = async (ctx) => {
	if (ctx.header.authorization) {
		const jwtstr = ctx.header.authorization.split('Bearer ')[1]

		try {
			const jwtdata = jwt.verify(jwtstr, jwtConfig.secret)
			return { jwtdata }
		} catch (error) {
			if (error.name === 'TokenExpiredError') {
			    throw new ApiError(ApiErrorNames.TOKEN_EXPIRED)
			} else {
				throw new ApiError(ApiErrorNames.TOKEN_INVALID)
			}
		}

	}
	return { jwtdata: null }
}
